<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('cisrf_create_token'))
{
    function cisrf_create_token($limit_token_life = 300, $len_token_name = 10, $alphabet = 'qwertyuopasdfghjklizxcvbnm')
    {
        // create a random token name
        $len_token_name = ($len_token_name <= strlen($alphabet)) ? $len_token_name : strlen($alphabet);
        $token_name = substr(str_shuffle($alphabet), 0, $len_token_name);

        // create a random token value
        $token = md5(microtime() . $token_name);

        $CI =& get_instance();
        
        // check session values
        $token_time = $CI->session->userdata('CISRF_token_time_' . uri_string());
        if (empty($token_time) || (time() - $token_time) > $limit_token_life) {
            // set the session values
            $CI->session->set_userdata(array(
                'CISRF_token_name_' . uri_string() => $token_name,
                'CISRF_token_' . uri_string() => $token,
                'CISRF_token_time_' . uri_string() => time()
            ));
        }
    }
}

// ------------------------------------------------------------------------

if ( ! function_exists('cisrf_token_name'))
{
    function cisrf_token_name()
    {
        $CI =& get_instance();
        return $CI->session->userdata('CISRF_token_name_' . uri_string());
    }
}

// ------------------------------------------------------------------------

if ( ! function_exists('cisrf_token'))
{
    function cisrf_token()
    {
        $CI =& get_instance();
        return $CI->session->userdata('CISRF_token_' . uri_string());
    }
}

// ------------------------------------------------------------------------

if ( ! function_exists('cisrf_token_is_valid'))
{
    function cisrf_token_is_valid($callback_name = '_cisrf_token_is_valid')
    {
        $CI =& get_instance();
        if ($CI->session->userdata('CISRF_token_' . uri_string()) != $CI->input->post(CISRF_token_name()))
        {
            $CI->form_validation->set_message($callback_name, 'Potential CSRF attack! What were you up to?');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
}

/* End of file cisrf_helper.php */
/* Location: ./system/application/helpers/cisrf_helper.php */
